package com.yzg.sign.project.common;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import sun.plugin2.os.windows.Windows;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class TianCongUtils
{

    public static final String appid = "56978fa44a08bd3c9b04898a";
    public static final String appkey = "VjZ3VvD5Vra6WQD4XjR3WQa3VwHZK4LqsyxvCZ==";


    private static String getToken()
    {
        return DigestUtils.md5Hex(appid+"&"+appkey);
    }






   public static String register(String userId)
   {
       String url = "http://119.3.22.24:3997/registeruser?userid=userId&token=Token";

       String res =   HttpClientUtil.doPost(url.replace("userId",userId).replace("Token",getToken()));
       return res;
   }

    public static String addSample(String userId, String step, String content, File file)
    {
        String TWO_HYPHENS = "--";
        String BOUNDARY = "*****";
        String END = "\r\n";
        String CHARSET = "UTF-8";


        Map<String, String> params = new HashMap<>();
        params.put("userid",userId);
        params.put("content",content);
        params.put("appkey",appkey);
        params.put("token",getToken());
        URL url = null;
        String url1 = null;
        if(!StringUtils.isEmpty(step))
        {
            params.put("step",step);
            url1 = "http://119.3.22.24:3997/addsample";
        }else{
            url1 = "http://119.3.22.24:3997/verifymodel";
        }
        try {
            url = new URL(url1);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
             StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(TWO_HYPHENS);
                sb.append(BOUNDARY);
                sb.append(END);
                sb.append("Content-Disposition: form-data; name=\""
                        + entry.getKey() + "\"" + END);
                sb.append("Content-Type: text/plain; charset=" + CHARSET + END);
                sb.append("Content-Transfer-Encoding: 8bit" + END);
                sb.append(END);
                sb.append(entry.getValue());
                sb.append(END);
            }

                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ file.getName() + "\"\r\n");
                sb.append("Content-Type:application/octet-stream\r\n\r\n");
                byte[] data = sb.toString().getBytes();
                out.write(data);
                DataInputStream in = new DataInputStream(new
                        FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                out.write("\r\n".getBytes()); //多个文件时，二个文件之间加入这个
                in.close();

            out.write(end_data);
            out.flush();
            out.close();
// 定义 BufferedReader 输入流来读取 URL 的响应
            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }
            return stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String trainmodel(String userId)
    {
        String url = "http://119.3.22.24:3997/trainmodel?userid=userId&token=Token";

        String res =   HttpClientUtil.doPost(url.replace("userId",userId).replace("Token",getToken()));
        System.out.println(res);
        return res;
    }


    public static String verifymodel(String userId, int step, String content, File file)
    {
        String url = "http://119.3.22.24:3997/verifymodel";
        Map<String, Object> params = new HashMap<>();
        params.put("userid",userId);
        params.put("content",content);
        params.put("file",file);
        params.put("appkey",appkey);
        params.put("token",getToken());
        String res = null;
        try {
            res = HttpClientUtil.postParam(params,url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }







}
